<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true">
				<el-form-item>
					<el-input v-model="keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="warning" v-on:click="keywordQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表v-loading="listLoading"-->
		<el-table :data="tableDatas" v-loading="listLoading" @selection-change="handleSelectionChange" highlight-current-row
			style="width: 100%;">
			<!--多选框-->
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="70" label="序号">
			</el-table-column>
			<el-table-column prop="articlePic" label="文章封面图片" width="120">
				<template scope="scope">
					<el-image style="width: 100px; height: 100px" :src="scope.row.articlePic" ></el-image>
				</template>
			</el-table-column>
			<el-table-column prop="articleName" label="文章名称" width="120">
			</el-table-column>
			<el-table-column prop="articleTag" label="文章标签" width="150">
			</el-table-column>
			<el-table-column prop="typeName" label="文章类型" width="150">
			</el-table-column>
			<el-table-column prop="articleState" label="文章状态" width="200">
				<template scope="scope">
					<span v-if="scope.row.articleState == 1" style="color: green;">发布</span>
					<span v-else-if="scope.row.articleState == 2" style="color: red;">弃用</span>
					<span v-else style="color: grey;">草稿</span>
				</template>
			</el-table-column>
			<el-table-column prop="topState" label="是否置顶" width="200">
				<template scope="scope">
					<span v-if="scope.row.topState == 1" style="color: green;">置顶</span>
					<span v-else style="color: red;">不置顶</span>
				</template>
			</el-table-column>
			<el-table-column prop="publishName" label="发布人" width="200">
			</el-table-column>
			<el-table-column prop="createTime" label="创建时间" width="200">
			</el-table-column>
			<el-table-column prop="updateTime" label="更新时间" width="200">
			</el-table-column>
			<el-table-column prop="articleReadCount" label="阅读量" width="200">
			</el-table-column>
			<el-table-column prop="articleStarNum" label="点赞数" width="200">
			</el-table-column>
			<el-table-column prop="articleCommentNum" label="评论数" width="200">
			</el-table-column>

			<el-table-column label="操作" width="200" fixed="right">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" :disabled="this.sels.length === 0" @click="handlePatchDel">批量删除</el-button>
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
				:page-sizes="[5, 10, 15]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
				:total="totals" style="float:right;">
			</el-pagination>
		</el-col>







		<!--添加或修改界面-->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="文章图片" prop="articlePic">
					<el-upload class="upload-demo" action="http://localhost:8080/minio" name="file"
						:on-remove="handleRemove" :on-success="handleSuccess" :on-exceed="exceed" :file-list="fileList"
						:limit=1 accept=".jpg,.jpeg,.png,.gif" list-type="picture">
						<el-button size="small" type="primary">点击上传</el-button>
						<div slot="tip" class="el-upload__tip">只能上传指定类型的图片</div>
					</el-upload>
				</el-form-item>
				<el-form-item label="文章名称">
					<el-input v-model="saveForm.articleName" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="文章标签" prop="articleTag">
					<el-input v-model="saveForm.articleTag" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="文章类型">
					<el-cascader v-model="saveForm.articleType" :options="typeTree" :props="{
						checkStrictly: true,
						label: 'typeName',
						value: 'id'
					}" placeholder="选择你的文章类型" clearable></el-cascader>
				</el-form-item>

				<el-form-item label="文章状态">
					<template>
						<el-radio v-model="saveForm.articleState" :label="1">可用</el-radio>
						<el-radio v-model="saveForm.articleState" :label="2">弃用</el-radio>
						<el-radio v-model="saveForm.articleState" :label="0">草稿</el-radio>
					</template>
				</el-form-item>
				<el-form-item label="是否置顶">
					<template>
						<el-radio v-model="saveForm.topState" :label="1">置顶</el-radio>
						<el-radio v-model="saveForm.topState" :label="0">不置顶</el-radio>
					</template>
				</el-form-item>
				<el-form-item label="文章备注">
					<!-- <el-input v-model="saveForm.articleRemark" auto-complete="off"></el-input> -->
					<el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="saveForm.articleRemark">
					</el-input>
				</el-form-item>
				<el-form-item label="文章评论" prop="articleContent">
					<div class="edit_container">
						<quill-editor v-model="saveForm.articleContent" :options="quillOption">
						</quill-editor>
					</div>
				</el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit">提交</el-button>
			</div>
		</el-dialog>





	</section>
</template>


<script>
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config';

// 工具栏配置
const toolbarOptions = [
	["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
	["blockquote", "code-block"], // 引用  代码块-----['blockquote', 'code-block']
	[{ header: 1 }, { header: 2 }], // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
	[{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
	[{ script: "sub" }, { script: "super" }], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
	[{ indent: "-1" }, { indent: "+1" }], // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
	[{ direction: "rtl" }], // 文本方向-----[{'direction': 'rtl'}]
	[{ size: ["small", false, "large", "huge"] }], // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
	[{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
	[{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
	[{ font: [] }], // 字体种类-----[{ font: [] }]
	[{ align: [] }], // 对齐方式-----[{ align: [] }]
	["clean"], // 清除文本格式-----['clean']
	["image", "link"] // 链接、图片、视频-----['link', 'image', 'video']
];

export default {
	components: {
		quillEditor
	},
	data() {
		return {
			quillOption: quillConfig,
			typeTree: [],
			//1.分页查询相关数据
			totals: 0,//总记录条数
			currentPage: 1,//当前页,要传递到后台的
			pageSize: 5, //每页显示多少条
			tableDatas: [], //当前页数据
			listLoading: false,

			//2.高级查询相关数据
			keyword: '',
			title: "",
			//3.删除相关数据

			//4.批量删除相关数据
			sels: [], //存储多选记录

			//5.添加和修改相关数据
			saveFormVisible: false,
			saveForm: {
				id: null,
				articlePic: "",
				articleName: "",
				articleTag: "",
				articleType: null,
				articleState: 0,
				topState: 0,
				articleRemark: "",
				articleContent: "",



			},
			fileList: [],
			imgUrl:"",

			editorOption: {
				modules: {
					//工具栏定义的
					toolbar: toolbarOptions
				},
				//主题
				theme: "snow",
				placeholder: "请开始书写您的博客内容..."
			},

			//6.添加和修改校验规则-表单项校验
			saveFormRules: {
				article_name: [
					{ required: true, message: '请输入类型名称', trigger: 'blur' }
				],
				publish_id: [
					{ required: true, message: '请输入类型名称', trigger: 'blur' }
				],
				article_type: [
					{ required: true, message: '请输入类型名称', trigger: 'blur' }
				]
			},
			preUrl: "http://minio.java.itsource.cn/java0820/"

		}
	},
	methods: {
		//1.分页查询相关方法
		//1.1.获取列表数据
		getTableData() {
			this.listLoading = true;
			this.$http.post("/article", {
				"currentPage": this.currentPage,
				"pageSize": this.pageSize,
				"keyword": this.keyword
			}).then(res => {
				this.tableDatas = res.data.list
				this.totals = res.data.total
				this.listLoading = false
				console.log(res.data.list);
			}).catch(res => {
				this.$message("请求错误,请稍后重试")
				this.listLoading = false
			})
		},
		//1.2.选择第几页时触发
		handleCurrentChange(currentPage) {
			this.currentPage = currentPage
			this.getTableData()
		},
		//1.3.选择每页显示记录条数时触发
		handleSizeChange(pageSize) {
			this.pageSize = pageSize
			this.getTableData()
		},

		//2.高级查询相关方法
		keywordQuery() {

			// this.$http.get("/user/keywordQuery",{

			// 	"keyword":this.keyword
			// }).then(res=>{
			// 	this.tableDatas=res.data.list
			// }).catch(res=>{

			// 	this.$message("请求错误,请稍后重试")
			// })
			this.currentPage = 1;
			/* 初始化当前页面,高级查询应当从第一页开始搜索 */
			this.getTableData();


		},

		//3.删除相关方法
		handleDel(row) {
			
			var filename = row.articlePic.substring(row.articlePic.lastIndexOf("/") + 1)
			this.$confirm('确认是否删除该文件', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.$http.delete("/article/" + row.id).then(res => {
					if (res.data.success) {
						this.$message.success("删除成功")
						this.getTableData()
					} else {

						this.$message.warning("删除失败")
					}
				})
				this.$http.delete("/minio/"+filename).then(res=>{
					if (res.data.success) {
						this.$message.success("删除成功")
						this.getTableData()
					} else {

						this.$message.warning("删除失败")
					}
				})
			}).catch(() => {

				this.$message.danger("请求错误,请稍后重试")
			});
			
		},


		//4.批量删除相关方法
		//4.1.选项改变时触发
		handleSelectionChange(val) {
			this.sels = val
			/* val存放的是所选项的对象 */

		},
		//4.2.批量删除
		handlePatchDel() {
			/* 原始方法 */
			// let arr = [];
			// for(let i=0;i<this.sels.length;i++){
			// 	arr.push(this.sels[i].id);
			// }

			/* 使用map 对数组进行遍历获取id*/
			var arr = this.sels.map(obj => obj.id)
			var namearr= this.sels.map(obj=>obj.articlePic.substring(obj.articlePic.lastIndexOf("/") + 1))
			console.log(arr);
			this.$confirm('确认是否删除选中的文件', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.$http.patch("/article", arr).then(res => {
					if (res.data.success) {
						this.$message.success("删除成功")
						this.getTableData()
					} else {

						this.$message.warning("删除失败")
					}
				})
				this.$http.patch("/minio",namearr).then(res=>{
					if (res.data.success) {
						this.$message.success("删除成功")
						this.getTableData()
					} else {

						this.$message.warning("删除失败")
					}
				})
			}).catch(() => {
				this.$message.danger("请求错误,请稍后重试")
			});
			

		},

		//5.添加和修改相关方法
		//5.1.点击添加弹出对话框
		handleAdd() {
			this.title = "上传文章"
			this.fileList = []
			/* 为了处理后端删掉了但是前端不变的问题,需要删掉fileList中的数据 */
			this.saveForm = {
				id: null,
				articlePic: "",
				articleName: "",
				articleTag: "",
				articleType: null,
				articleState: 0,
				topState: 0,
				articleRemark: "",
				articleContent: "",
			}
			this.getTypeTree()
			this.saveFormVisible = true;
		},
		//5.2.点击修改弹出对话框
		handleEdit(row) {
			this.title = "修改文章"
			/* 为了处理后端删掉了但是前端不变的问题,需要删掉fileList中的数据 */
			this.saveForm = Object.assign({}, row);
			/* 深拷贝,将row的值拷贝到一个新的对象,这样数据不会受到双向绑定的影响 */
			// this.saveForm=JSON.parse(JSON.stringify(row))
			/* 另一种方式,将对象转换为一个json字符串进行传参,不会影响原本的值,也可以达到深拷贝的效果 */
			this.getTypeTree()
			this.fileList = []
			if (this.saveForm.articlePic) {
				this.fileList.push({ "url": row.articlePic })
			}
			this.saveFormVisible = true;

		},
		//5.3.提交表单数据操作数据库
		saveSubmit() {
			this.$refs.saveForm.validate((valid => {
				/* 
				校验语句,根据表单属性rules的值saveFormRules来决定表单的填写规则(哪些必须填哪些可以不填),
				这里符合规则则结果值是true,不满足就是false,所以在满足时才需要发送请求,不满足则不发送
				*/
				if (valid) {

					var temp = this.saveForm.articleType
					if (temp == null || temp.length == 0) {
						this.saveForm.articleType = null
						/* 当获取到的值 为空或不为数组时,将其值直接赋予给parentId*/
					} else if (temp.length) {
						this.saveForm.articleType = temp[temp.length - 1]
						/* 当获取到的值为数组时(这里使用temp.length来作为判断条件,是因为,有数组长度是数组,这个表达式为true,没有则为false,他也不是数组),将最后一个元素赋予给parentid */
					}
					this.$http.put("/article", this.saveForm).then(res => {
						console.log(res);
						this.saveFormVisible = false;
						if (res.data.success) {
							this.$message.success("添加成功")
							this.getTableData()
							

						} else {
							this.$message.warning("添加失败")

						}
					}).catch(res => {
						this.$message("请求失败")
						this.saveFormVisible = false;

					})
				} else {
					this.$message.error("校验失败");
				}
			}))


		},
		getTypeTree() {
			this.$http.get("/articleType/typeTree").then(ref => {

				this.typeTree = ref.data;
			}).catch(ref => {
				this.$message.error("请求错误")
			})
		},
		handleAvatarSuccess(res, file) {
			this.imageUrl = URL.createObjectURL(file.raw);
		},
		/* 上传成功的钩子函数 */
		handleSuccess(response, file, fileList) {
			this.fileList = []
			/* 先清空fileList,以免出现错误 */

			this.saveForm.articlePic = this.preUrl + response.data

			this.fileList.push({ "url": this.preUrl + response.data })

		},
		/* 删除成功的钩子函数 */
		handleRemove(file, fileList) {
			console.log(file);
			this.fileList = []
			/* 删除的时候清空fileList中的数据 */
			this.saveForm.articlePic = '';
			var filename = file.url.substring(file.url.lastIndexOf("/") + 1);
			/* 先获取文件名 */
			this.$http.delete("/minio/" + filename).then(res => {
				if (res.data.success) {
					this.$message.success("删除成功")

				} else {
					this.$message.error("删除失败")
				}
			})

		},
		exceed() {
			this.$message.error("超出可上传数量")
		}



	},
	mounted() {
		this.getTableData();
		console.log(this.tableDatas);
	}
}

</script>

<style scoped></style>
